<template>
  <div class="personal-center">
    <div class="personal-header">
      <h2>个人中心</h2>
    </div>

    <!-- 个人信息 -->
    <el-card class="info-card">
      <template #header>
        <div class="card-header">
          <h2>个人信息</h2>
        </div>
      </template>
      <el-form
        :model="userInfo"
        :rules="userInfoRules"
        ref="userInfoFormRef"
        label-width="100px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="userInfo.username" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="真实姓名" prop="realName">
          <el-input v-model="userInfo.realName" placeholder="请输入真实姓名" />
        </el-form-item>
        <el-form-item label="角色" prop="role">
          <el-select v-model="userInfo.role" placeholder="请选择角色">
            <el-option
              v-for="role in roleOptions"
              :key="role.value"
              :label="role.label"
              :value="role.value"
              :disabled="role.disabled"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitUserInfoForm">提交</el-button>
          <el-button @click="resetUserInfoForm">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 修改密码 -->
    <el-card class="password-card">
      <template #header>
        <div class="card-header">
          <h2>修改密码</h2>
        </div>
      </template>
      <el-form
        :model="passwordForm"
        :rules="passwordRules"
        ref="passwordFormRef"
        label-width="100px"
      >
        <el-form-item label="旧密码" prop="oldPassword">
          <el-input
            v-model="passwordForm.oldPassword"
            type="password"
            show-password
            placeholder="请输入旧密码"
          />
        </el-form-item>
        <el-form-item label="新密码" prop="newPassword">
          <el-input
            v-model="passwordForm.newPassword"
            type="password"
            show-password
            placeholder="请输入新密码"
          />
        </el-form-item>
        <el-form-item label="确认新密码" prop="confirmPassword">
          <el-input
            v-model="passwordForm.confirmPassword"
            type="password"
            show-password
            placeholder="请再次输入新密码"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitPasswordForm">提交</el-button>
          <el-button @click="resetPasswordForm">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { ElMessage, type FormInstance, type FormRules } from 'element-plus';
import { useRouter } from 'vue-router';
import { useUserStore, type UpdateUserData } from '@/stores/api/user';
import { useRoleStore, type Role } from '@/stores/project/role';
import axios from '@/plugins/axios';

const userStore = useUserStore();
const roleStore = useRoleStore();
const router = useRouter();

// 个人信息
const userInfo = ref({
  id: 0,
  username: '',
  realName: '',
  role: '',
});

// 角色选项
const roleOptions = ref<Role[]>(roleStore.roles);

// 个人信息表单引用
const userInfoFormRef = ref<FormInstance>();

// 个人信息校验规则
const userInfoRules = ref<FormRules>({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, message: '用户名长度至少3位', trigger: 'blur' },
  ],
  realName: [
    { required: true, message: '请输入真实姓名', trigger: 'blur' },
  ],
  role: [
    { required: true, message: '请选择角色', trigger: 'change' },
  ],
});

// 密码表单
const passwordForm = ref({
  oldPassword: '',
  newPassword: '',
  confirmPassword: '',
});

// 密码表单引用
const passwordFormRef = ref<FormInstance>();

// 密码校验规则
const passwordRules = ref<FormRules>({
  oldPassword: [
    { required: true, message: '请输入旧密码', trigger: 'blur' },
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '密码长度至少6位', trigger: 'blur' },
  ],
  confirmPassword: [
    { required: true, message: '请确认新密码', trigger: 'blur' },
    {
      validator: (rule: any, value: string, callback: any) => {
        if (value !== passwordForm.value.newPassword) {
          callback(new Error('两次输入的密码不一致'));
        } else {
          callback();
        }
      },
      trigger: 'blur',
    },
  ],
});

// 加载个人信息
const fetchUserInfo = async () => {
  if (!userStore.user?.id) {
    ElMessage.error('用户未登录');
    router.push('/login');
    return;
  }
  try {
    const userData = await userStore.fetchUserInfo(userStore.user.id);
    userInfo.value = {
      id: userData.id,
      username: userData.username || '未知',
      realName: userData.realName || '未设置',
      role: userData.role || 'STUDENT',
    };
  } catch (error) {
    ElMessage.error('加载个人信息失败');
  }
};

// 提交用户信息
const submitUserInfoForm = async () => {
  if (!userInfoFormRef.value) return;
  userInfoFormRef.value.validate(async (valid) => {
    if (valid) {
      if (!userStore.user?.id) {
        ElMessage.error('用户未登录');
        router.push('/login');
        return;
      }
      try {
        const updateData: UpdateUserData = {
          id: userInfo.value.id,
          username: userInfo.value.username,
          realName: userInfo.value.realName,
          role: userInfo.value.role,
          password: userStore.user.password, // 保持原密码不变
        };
        await userStore.updateUser(updateData);
        ElMessage.success('用户信息修改成功');
      } catch (error) {
        ElMessage.error('用户信息修改失败');
      }
    }
  });
};

// 重置用户信息表单
const resetUserInfoForm = () => {
  if (!userInfoFormRef.value) return;
  userInfoFormRef.value.resetFields();
  fetchUserInfo(); // 重新加载原始用户信息
};

// 提交修改密码
const submitPasswordForm = async () => {
  if (!passwordFormRef.value) return;
  passwordFormRef.value.validate(async (valid) => {
    if (valid) {
      if (!userStore.user?.id) {
        ElMessage.error('用户未登录');
        router.push('/login');
        return;
      }
      // 检查旧密码是否匹配
      if (passwordForm.value.oldPassword !== userStore.user.password) {
        ElMessage.error('旧密码不正确');
        return;
      }
      try {
        const updateData: UpdateUserData = {
          id: userStore.user.id,
          username: userStore.user.username,
          realName: userStore.user.realName,
          role: userStore.user.role,
          password: passwordForm.value.newPassword,
        };
        await userStore.updateUser(updateData);
        ElMessage.success('密码修改成功');
        resetPasswordForm();
      } catch (error) {
        ElMessage.error('密码修改失败');
      }
    }
  });
};

// 重置密码表单
const resetPasswordForm = () => {
  if (!passwordFormRef.value) return;
  passwordFormRef.value.resetFields();
};

// 初始化加载
onMounted(() => {
  fetchUserInfo();
});
</script>

<style scoped>
.personal-center {
  width: 80%;
  margin: 40px auto 0 auto;
}

.personal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.personal-header h2 {
  font-size: 24px;
  color: #333;
  flex-grow: 1;
  text-align: center;
}

.info-card,
.password-card {
  margin: 20px 0;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  background-color: #ffffff;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h2 {
  font-size: 24px;
  color: #333;
  margin: 0;
}

.el-form {
  padding: 20px;
}

.el-button {
  margin-right: 10px;
}

.el-select {
  width: 100%;
}
</style>